<?php


class OopSwoole{
    public $server = null;

    public $eventList = [
        'request'=>'onRequest',
        'task'=>'onTask',
        'finish'=>'onFinish',
    ];

    public $config = [
        'worker_num'=>4
    ];

    public function __construct($host,$port)
    {
        $this->server = new \Swoole\Http\Server($host,$port);
    }

    public function set($configName,$configValue)
    {
        $this->config[$configName] = $configValue;
    }

    public function onRequest(\Swoole\Http\Request $request,\Swoole\Http\Response $response)
    {

        if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
            $response->end();
            return;
        }

        $this->server->task("刘恒哦");
        $response->header("Content-Type", "text/html; charset=utf-8");
        $response->end("hello Word");
    }

    /**
     * 处理异步任务(此回调函数在task进程中执行)
     * @param $serv
     * @param $task_id
     * @param $from_id
     * @param $data
     */
    public function onTask($serv, $task_id, $from_id, $data)
    {
        sleep(5);
        echo "，taskId为：{$task_id}\n";
        $this->server->finish("{$data}   数据执行完成");
    }

    /**
     * 异步任务完成
     * @param $serv
     * @param $task_id
     * @param $data
     */
    public function onFinish($serv, $task_id, $data)
    {
        echo "task执行完成，taskID为：{$task_id},返回数据为：{$data}\n";
    }

    public function setEvent($eventName,$functionName)
    {
        $this->eventList[$eventName] = $functionName;
    }


    public function start(){
        $this->server->set($this->config);
        foreach ($this->eventList as $eventName=>$functionName){
            $this->server->on($eventName,[$this,$functionName]);
        }
        $this->server->start();
    }


}

$oopServer = new OopSwoole('0.0.0.0','9501');
$oopServer->set('task_worker_num',4);
$oopServer->start();
